package backtrack;

import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kaho
 * @since 2021/1/4
 */
public class _46_全排列 {

    /**
     *
     给定一个 没有重复 数字的序列，返回其所有可能的全排列。

     示例:

     输入: [1,2,3]
     输出:
     [
     [1,2,3],
     [1,3,2],
     [2,1,3],
     [2,3,1],
     [3,1,2],
     [3,2,1]
     ]
     * @param nums
     * @return
     */
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        int length = nums.length;
        if (length == 0) {
            return result;
        }

        boolean[] used = new boolean[length];
        List<Integer> path = new ArrayList<>();
        dfs(nums,length, 0, used,path,result);
        return result;
    }

    private void dfs(int[] nums, int length, int i, boolean[] used,
                     List<Integer> path, List<List<Integer>> result) {
        if (length == i){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int j = 0; j < length; j++) {
            if(!used[j]){
                path.add(nums[j]);
                used[j] = true;
                dfs(nums, length, i+1, used, path, result);
                used[j] = false;
                path.remove(path.size() - 1);
            }
        }
    }

}
